package org.linlinjava.litemall.db.service;

import org.linlinjava.litemall.db.dao.LitemallGrouponRulesMapper;
import org.linlinjava.litemall.db.domain.LitemallGoods;
import org.linlinjava.litemall.db.domain.LitemallGrouponExample;
import org.linlinjava.litemall.db.domain.LitemallGrouponRules;
import org.linlinjava.litemall.db.domain.LitemallGrouponRulesExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class LitemallRouponRulesServiceImpl implements LitemallRouponRulesService {

    @Resource
    LitemallGrouponRulesMapper litemallGrouponRulesMapper;

    @Autowired
    LitemallGoodsService litemallGoodsService;

    @Override
    public List<LitemallGrouponRules> getAll(Integer code, Integer page, Integer pageSize) {
        LitemallGrouponRulesExample example = new LitemallGrouponRulesExample();
        LitemallGrouponRulesExample.Criteria criteria = example.createCriteria();
        criteria.andDeletedEqualTo(false);
        if(code != null){
            criteria.andGoodsIdEqualTo(code);
        }
        return litemallGrouponRulesMapper.selectByExample(example);
    }

    @Override
    public boolean addRules(LitemallGrouponRules rules) {
        rules.setDeleted(false);
        rules.setAddTime(new Date());
        LitemallGoods goods = litemallGoodsService.findById(rules.getGoodsId());
        if(goods == null){
            return false;
        }
        rules.setGoodsName(goods.getName());
        rules.setPicUrl(goods.getPicUrl());;
        return litemallGrouponRulesMapper.insert(rules) > 0 ? true : false;
    }

    @Override
    public boolean update(LitemallGrouponRules rules) {
        LitemallGoods goods = litemallGoodsService.findById(rules.getGoodsId());
        if(goods == null){
            return false;
        }
        rules.setGoodsName(goods.getName());
        rules.setPicUrl(goods.getPicUrl());;
        rules.setUpdateTime(new Date());
        return litemallGrouponRulesMapper.updateByPrimaryKey(rules) > 0 ? true : false;
    }

    @Override
    public boolean delete(LitemallGrouponRules rules) {
        rules.setDeleted(true);
        return litemallGrouponRulesMapper.updateByPrimaryKey(rules) > 0 ? true : false;
    }

    @Override
    public LitemallGrouponRules getRules(Integer id) {
        return litemallGrouponRulesMapper.selectByPrimaryKey(id);
    }
}
